#!/bin/bash
#2020年7月13日20:37:02
#auto congfig nginx virtual hosts
#by author www.jfedu.net
########################
NGX_VHOST="$1"
NGX_VER="1.16.0"
NGX_YUM="yum install -y"
NGX_SRC="nginx-${NGX_VER}"
NGX_DIR="/usr/local/nginx"
NGX_SOFT="${NGX_SRC}.tar.gz"
NGX_URL="http://nginx.org/download"
NGX_ARGS="--user=www --group=www --with-http_stub_status_module"
if [ $# -eq 0 ];then
	echo -e "\033[32m---------------\033[0m"
	echo -e "\033[32mUsage:{/bin/sh $0 v1.jf.com|v2.jf.com|help}\033[0m"
	exit 1
fi

if [ ! -f $NGX_DIR/sbin/nginx ];then
	#Install nginx web
	$NGX_YUM wget gzip tar make gcc
	$NGX_YUM pcre pcre-devel zlib-devel
	wget -c $NGX_URL/$NGX_SOFT
	ls -l $NGX_SOFT
	tar -xzvf $NGX_SOFT
	cd $NGX_SRC/
	useradd -s /sbin/nologin www -M
	./configure --prefix=$NGX_DIR/ $NGX_ARGS 
	make
	make install
	$NGX_DIR/sbin/nginx
	ps -ef|grep nginx
	netstat -tnlp|grep 80
	setenforce 0
	systemctl stop firewalld.service
fi

#Config nginx virtual hosts
cd $NGX_DIR/conf/
\cp nginx.conf nginx.conf.bak
grep "domains" nginx.conf >/dev/null
if [ $? -ne 0 ];then
	cat>nginx.conf<<-EOF
	worker_processes  1;
	events {
	    worker_connections  1024;
	}
	http {
	    include       mime.types;
	    default_type  application/octet-stream;
	    sendfile        on;
	    keepalive_timeout  65;
	    include domains/*;
	}
	EOF
	mkdir -p domains
fi

cd domains/
if [ ! -f $NGX_VHOST ];then
	cat>$NGX_VHOST <<-EOF
	server {
	        listen       80;
	        server_name  $NGX_VHOST;
	        location / {
	            root   html/$NGX_VHOST;
	            index  index.html index.htm;
	        }
	        error_page   500 502 503 504  /50x.html;
	        location = /50x.html {
	            root   html;
	        }
	}
	EOF
	mkdir -p $NGX_DIR/html/$NGX_VHOST/
	cd $NGX_DIR/html/$NGX_VHOST/
	cat>index.html<<-EOF
	<html>
	<h1>$NGX_VHOST Test Pages</h1>
	<hr color=red>
	</html>
	EOF
	echo -e "\033[32mThe $NGX_VHOST Add success.\033[0m"
	echo -e "\033[32m---------------\033[0m"
	cat $NGX_DIR/conf/domains/$NGX_VHOST
	echo -e "\033[32m---------------\033[0m"
	$NGX_DIR/sbin/nginx -t
	$NGX_DIR/sbin/nginx -s reload
else
	echo -e "\033[32mThe $NGX_VHOST already exists.\033[0m"
	echo -e "\033[32m---------------\033[0m"
	cat $NGX_DIR/conf/domains/$NGX_VHOST
fi
